package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.LoginDto;
import com.example.springboot.controller.request.AdminPageRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.controller.request.PasswordRequest;
import com.example.springboot.entity.Admin;
import com.example.springboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/list")
    public Result list(){
        List<Admin> list = adminService.list();
        return Result.success(list);
    }

    /**
     * 分页查询
     * @return
     */
    @GetMapping("/page")
    public Result page(AdminPageRequest pageRequest){
        return Result.success(adminService.page(pageRequest));
    }
    /**
     * 新增用户
     * 前端如何把数据发送给给后台：是通过HTTP的方式，通过POST请求，把JSON数据发送给后台接口，后台接口接收到数据之后，转换成JAVA的对象，然后把Java对象，存到数据库中。
     */
    @PostMapping("/save")
    public Result save(@RequestBody Admin obj){
        adminService.save(obj);
        return Result.success();
    }
    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Admin obj = adminService.getById(id);
        return Result.success(obj);
    }

    /**
     * 修改数据
     */
    @PutMapping("/update")
    public Result update(@RequestBody Admin obj){
        adminService.update(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        adminService.deleteById(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request){
        LoginDto login = adminService.login(request);
        return Result.success(login);
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @PutMapping("/password")
    public Result savePassword(@RequestBody PasswordRequest request){
        adminService.changePass(request);
        return Result.success();
    }
}
